package hou.fun.DownloadGirls;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author houweitao
 * @date 2016年11月5日下午5:53:52
 */

public class PhotoDownload implements Runnable {
	private static final Logger log = LoggerFactory.getLogger(PhotoDownload.class);
	private String photo;
	private DownloadSexyChinese download;
	private Sinagl singal;
	private static final String downloadPath = "photos";

	public PhotoDownload(String photo, DownloadSexyChinese download, Sinagl singal) {
		this.photo = photo;
		this.download = download;
		this.singal = singal;
	}

	@Override
	public void run() {
		log.info("download.." + photo);
		String name = getName(photo);
		if (name == null) {
			singal.finish();
			return;
		}

		try {
			URL url = new URL(photo);
			try {
				URLConnection uc = url.openConnection();
				uc.setConnectTimeout(5 * 1000);
				String referer = url.getProtocol() + "://" + url.getHost();
				uc.setRequestProperty("Referer", referer);
				uc.setRequestProperty("User-Agent",
						"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36"); // 模拟ie浏览器
				uc.setRequestProperty("Accept-Language", "zh-cn");
				// uc.setRequestProperty("Connection", "close"); // 不进行持久化连接

				InputStream is = uc.getInputStream();

				File file = new File(downloadPath);
				if (!file.exists())
					file.mkdirs();
				FileOutputStream out = new FileOutputStream(downloadPath + File.separator + name);
				int i = 0;
				while ((i = is.read()) != -1) {
					out.write(i);
				}
				is.close();
				log.info("success!! pageNum:" + download.getPageNum() + ",girlNum:" + download.getGirlNum()
						+ ",photoNum:" + download.getPhotoNum());
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			System.out.println("下载失败！");
		}
		singal.finish();
	}

	private String getName(String photo) {
		// http://crawling.zentora.net/data/xiuren/6c9fedacedb34571dde21c996a912cc5/thumb0008.jpg

		int last = photo.lastIndexOf('/');
		String left = photo.substring(0, last);
		String right = photo.substring(last + 1);

		int curLast = left.lastIndexOf('/');
		String leftRight = left.substring(curLast + 1);
		if (leftRight.length() < 6)
			return null;
		String begin = leftRight.substring(0, 6);

		return begin + "-" + right;
	}

}
